<?php
declare(strict_types=1);

namespace app\common\controller;

use app\common\service\AdminService;
use app\common\utils\JsonResponse;
use think\exception\HttpResponseException;
use app\common\enum\ResponseCode;
use think\App;
use ReflectionClass;
use ReflectionMethod;

class AdminController extends BaseController
{
    protected $adminId;
    protected AdminService $adminService;
    protected array $adminInfo = [];
    
    /**
     * 构造方法
     * @param App $app
     */
    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->adminService = new AdminService();
        
        // 从请求对象中获取管理员信息
        $this->adminId = request()->adminId;
        $this->adminInfo = request()->adminInfo;
        
        // 检查当前请求的权限
        $this->checkPermissionByAnnotation();
    }

    /**
     * 通过注解检查权限
     */
    protected function checkPermissionByAnnotation()
    {
        try {
            // 获取当前请求的控制器和方法
            $controller = request()->controller();
            $action = request()->action();
            
            // 获取当前方法的反射
            $class = new ReflectionClass(get_class($this));
            $method = $class->getMethod($action);
            
            // 获取方法的注释
            $doc = $method->getDocComment();
            if ($doc === false) {
                return;  // 没有注解则跳过权限检查
            }
            
            // 解析权限注解 @permission
            if (preg_match('/@permission\s+([^\s]+)/', $doc, $matches)) {
                $permission = $matches[1];
                if (!$this->hasPermission($permission)) {
                    throw new HttpResponseException(
                        JsonResponse::error('无权限访问', ResponseCode::FORBIDDEN)
                    );
                }
            }
        } catch (\ReflectionException $e) {
            // 反射异常时跳过权限检查
            return;
        }
    }
    
    /**
     * 判断是否有权限
     * @param string $permission
     * @return bool
     */
    protected function hasPermission(string $permission): bool
    {
        // 超级管理员拥有所有权限
        if (in_array('super_admin', $this->adminInfo['roles'] ?? [])) {
            return true;
        }
        
        // 检查是否有指定权限
        return in_array($permission, $this->adminInfo['permissions'] ?? []);
    }
} 